# -*- coding: utf-8 -*-
# article_search.py
# Created by Hardy on 25th, Jan
# Copyright 2017 杭州网川教育有限公司. All rights reserved.

import operator

from querier.esquerier import ElasticSearchQuerier
import utils.utils as utils


READ = 'read_num'
LIKE = 'like_num'
RATIO = 'like_read_ratio'
RELATIVE = 'relative'

DAYS = 15
MINIMUM_SHOULD_MATCH = '5<85% 10<9'
MAX_CHARACTER = 5
CATEGORY_CUTOFF = 0.9


class WechatArticleSearchQuerier(ElasticSearchQuerier):
    def __init__(self, es, index, doc_type, nlp_service=None):
        super(WechatArticleSearchQuerier, self).__init__(es, index, doc_type)
        self.nlp_service = nlp_service

    def _build_query(self, args):
        term = args.get('term', '')
        term = term if term else ''
        filters = args.get('filters', {})
        if filters is None:
            filters = {}
        order = args.get('order_by', utils.ORDER_OVERALL)
        from_ = args.get('from', 0)
        size_ = args.get('size', 10)
        highlight = args.get('highlight', False)

        # 处理查询文本
        term2, keywords, ex_keywords, weights = utils.process_query_term(term, self.nlp_service)
        ex_kw = utils.get_kv_json(ex_keywords, weights)
        ex_category = self.nlp_service.classify(keywords)
        ex_category = ex_category.get('classify', {})
        ex_category = utils.get_kv_json(ex_category.get('category', []), ex_category.get('category_prob', []))
        keywords = keywords * 2 + ex_keywords

        h_kv = {}

        for i in range(0, len(keywords)):
            if h_kv.get(keywords[i]) is None:
                h_kv[keywords[i]] = i

        query = self._gen_query(' '.join(keywords[0:10]), term, filters, order, from_, size_, highlight)
        keywords = [k[0] for k in sorted(h_kv.items(), key=operator.itemgetter(1))]
        return query, {}, {'keywords': keywords, 'order': order, 'ex_keywords': ex_kw, "ex_category": ex_category}

    def _build_result(self, es_result, param):
        keywords = param['keywords']
        ex_keywords = param['ex_keywords']
        ex_category = param['ex_category']
        order = param['order']
        total = es_result['hits']['total']
        articles = []
        for hit in es_result['hits']['hits']:
            articles.append(self.extract_result(hit, order))
        return {
            'total': total,
            'keywords': keywords,
            'ex_keywords': ex_keywords,
            'ex_category': ex_category,
            'articles': articles
        }

    def _gen_query(self, query_keywords, term, filters, order, from_, size_, highlight):
        must_clause = []
        should_clause = []
        filter_clause = []
        if filters:
            filter_clause = self._add_filter_clause(filter_clause, filters, 'biz_code', 'should')
            # filter_clause = self._add_filter_match(filter_clause, filters, 'biz_code', 'should')
            filter_clause = self._add_filter_clause(filter_clause, filters, 'has_copyright', 'should')
            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'publish_timestamp')
            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'read_num')
            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'like_num')
            filter_clause = self._add_filter_range_clause(filter_clause, filters, 'like_read_ratio')
            filter_clause = self._add_filter_clause(filter_clause, filters, 'category', 'should')
            if filters.get('category'):
                filters['category'] = [utils.category_smzdm_2_encode(c) for c in filters['category']]
                filters['category_weight'] = [CATEGORY_CUTOFF]
                filter_clause = self._add_filter_clause(filter_clause, filters, 'category', 'should')
                filter_clause = self._add_filter_range_clause(filter_clause, filters, 'category_weight')

            # filter_clause = self._add_filter_clause(filter_clause, filters, 'brands', 'should')
        if query_keywords.strip():
            must_clause.append(
                {
                    'multi_match': {
                        'analyzer': 'whitespace',
                        'query': query_keywords,
                        'fields': ['keywords', 'title_seg^3'],
                        # 'minimum_should_match': ""
                    }
                }
            )

        if term:
            term = term.strip()
            if len(term) <= 3:
                should_clause.append(
                    {
                        'match_phrase': {
                            "title": {
                                'query': term[0:MAX_CHARACTER],
                                # 'slop': 1,
                                'boost': 30,
                            },

                        }
                    }
                )
            else:
                should_clause.append(
                {
                    'match': {
                        "title": {
                            'query': term[0:MAX_CHARACTER],
                            # 'slop': 1,
                            'boost': 30,
                            'minimum_should_match': MINIMUM_SHOULD_MATCH
                        },

                    }
                }
            )

        query = {"query": {
            "bool": {
                # "must": must_clause,
                # "should": should_clause,
                "filter": filter_clause,
                # "must": {'bool': {}},
                # "minimum_should_match": 1
            }
        }, 'from': from_, 'size': size_}

        if must_clause:
            query['query']['bool']['must'] = must_clause

        if should_clause:
            query['query']['bool']['should'] = should_clause
            # query['query']['bool']['minimum_should_match'] = 1

        if order == 'read_num':
            query['sort'] = [{
                    '_script': {
                        "type": "number",
                        "script": {
                            "lang": "painless",
                            "inline": "Math.log(_score + 1.01) * (doc.read_num.value + 0.001)"
                        },
                        "order": "desc",
                    },
                }]
        elif order == 'like_num':
            query['sort'] = [
                {
                    '_script': {
                        "type": "number",
                        "script": {
                            "lang": "painless",
                            "inline": "Math.log(_score + 1.01) * (doc.like_num.value + 0.001)"
                        },
                        "order": "desc",
                    },

                }
            ]
        elif order == RATIO:
            query['sort'] = [
                {
                    '_script': {
                        "type": "number",
                        "script": {
                            "lang": "painless",
                            "inline": "Math.log(_score + 1.01) * (doc.like_read_ratio.value + 0.001)"
                        },
                        "order": "desc",
                    },

                }
            ]
        # elif order == 'relative':
        #     query['sort'] = [
        #         '_score',
        #         {'publish_timestamp': 'desc'}
        #     ]
        elif order == 'overall':
            query['sort'] = [
                {
                    '_script': {
                        "type": "number",
                        "script": {
                            "lang": "painless",
                            "inline": "_score  * Math.log(doc.read_num.value + 0.001)"
                        },
                        "order": "desc",
                    },
                }
            ]
        else:
            query['sort'] = [
                {'publish_timestamp': 'desc'},
                '_score'
            ]

        query['track_scores'] = True
        if highlight:
            query['highlight'] = {
                "pre_tags": ["<span class='keyword'>"],
                "post_tags": ["</span>"],
                "fields": {"keywords": {}, "title": {}}
            }
        else:
            query['highlight'] = {
                "pre_tags": [""],
                "post_tags": [""],
                "fields": {"keywords": {}, "title_seg": {}}
            }

        return query

    @staticmethod
    def _add_filter_match(must_clause, filters, key, cond='must'):
        if key in filters:
            if filters[key]:
                clause = []
                must_clause.append({
                    'bool': {cond: clause}
                })
                values = filters[key]
                if isinstance(values, str):
                    values = values.split(' ')
                for fk in values:
                    clause.append({'match': {key: {'query': fk, 'minimum_should_match': '20<100% 20<20'}}})
        return must_clause

    @staticmethod
    def _add_filter_clause(filter_clause, filters, key, cond='must'):
        if key in filters:
            if filters[key]:
                clause = []
                filter_clause.append({
                    'bool': {
                        cond: clause
                    }
                })
                for fk in filters[key]:
                    clause.append({'term': {key: fk}})
        return filter_clause

    @staticmethod
    def _add_filter_range_clause(filter_clause, filters, key):
        if key in filters:
            if filters[key]:
                clause = []
                filter_clause.append({
                    'bool': {
                        'must': clause
                    }
                })
                fk = filters[key]
                if not isinstance(fk, list) or len(fk) < 1:
                    pass
                else:
                    min_fk = fk[0]
                    if len(fk) >= 2:
                        max_fk = fk[1]
                    else:
                        max_fk = None
                    if min_fk is not None and min_fk != 'null':
                        clause.append({'range': {key: {"gte": min_fk}}})
                    if max_fk is not None and max_fk != 'null':
                        clause.append({'range': {key: {"lte": max_fk}}})
        return filter_clause

    @staticmethod
    def extract_result(hit, order):
        source_ = hit['_source']
        url = source_['url']
        likes = source_['like_num']
        reads = source_['read_num']

        score_ = hit['_score']
        keywords = source_['keywords']
        title = source_['title']
        highlight = hit.get('highlight')
        h_keywords = []

        if highlight:
            h_keywords = highlight.get('keywords')
            h_title = highlight.get('title_seg')
            if h_keywords:
                hk2 = [s.replace("<span class='keyword'>", '').replace("</span>", '') for s in h_keywords]
                if hk2:
                    h_keywords += [k for k in keywords if k not in hk2][0:10]
            if h_title:
                ht = [s.replace("<span class='keyword'>", '').replace("</span>", '') for s in h_title]
                if not h_keywords:
                    h_keywords = []
                if ht:
                    h_keywords = ht + h_keywords

        h_keywords = h_keywords if h_keywords else keywords[0:10]

        h_kv = {}

        for i in range(0, len(h_keywords)):
            if h_kv.get(h_keywords[i]) is None:
                h_kv[h_keywords[i]] = i

        h_keywords = [k[0] for k in sorted(h_kv.items(), key=operator.itemgetter(1))]

        return {
            'id': source_['id'],
            'biz_code': source_['biz_code'],
            'biz_name': source_['biz_name'],
            'title': title,
            'url': url,
            'msg_cdn_url': source_['msg_cdn_url'],
            'keywords': h_keywords,
            'read_num': reads,
            'like_num': likes,
            'has_copyright': source_.get('has_copyright'),
            'publish_timestamp': source_['publish_timestamp'],
            'crawler_timestamp': source_['crawler_timestamp'],
            'category': utils.category_smzdm_2_decode(source_.get('category', -1)),
            # 'category': source_.get('category_0'),
            'brands': []  # self.nlp_service.get_brands(source_.get('keywords', []))

        }
